<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  fetchGoodsRemovalList,
  fetchGoodsRemovalById,
  deleteGoodsRemoval,
} from '@/api/goodsRemovalApi'
import { formatDateTime } from '@/utils/dayjs'
import AddGoodsRemoval from './components/AddGoodsRemoval.vue'
import ViewHTML from '@/components/ViewHTML.vue'
import logger from '@/utils/logger'
import { REQUEST_STATE } from '@/constants'

// 控制添加/编辑对话框显示
const dialogVisible = ref(false)
const dialogTitle = ref('新增下架单据')
const currentRemoval = ref(null)
const isReviewMode = ref(false)
const isDetailMode = ref(false)

// 控制商品介绍预览对话框显示
const previewVisible = ref(false)
const previewContent = ref('')

// 表格数据和加载状态
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 查询条件
const queryFields = ref({
  goodsstopmJxsId: '',
  billState: '',
})

// 获取下架单据列表
const fetchRemovalData = async () => {
  loading.value = true
  try {
    const params = {
      queryFields: {
        goodsstopmJxsId: queryFields.value.goodsstopmJxsId,
        billState: queryFields.value.billState,
      },
      currentPage: currentPage.value,
      pageSize: pageSize.value,
    }
    const res = await fetchGoodsRemovalList(params)
    if (res.success) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取下架单据列表失败')
    }
  } catch (error) {
    logger.error('获取下架单据列表失败', error)
    ElMessage.error('获取下架单据列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRemovalData()
}

// 重置搜索
const resetSearch = () => {
  queryFields.value = {
    goodsstopmJxsId: '',
    billState: '',
  }
  currentPage.value = 1
  fetchRemovalData()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchRemovalData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchRemovalData()
}

// 打开添加对话框
const openAddDialog = () => {
  currentRemoval.value = null
  dialogTitle.value = '新增下架单据'
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await fetchGoodsRemovalById(row.goodsstopmJxsId)
    if (res.success) {
      currentRemoval.value = res.data
      dialogTitle.value = '编辑下架单据'
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取下架单据详情失败')
    }
  } catch (error) {
    logger.error('获取下架单据详情失败', error)
    ElMessage.error('获取下架单据详情失败')
  } finally {
    loading.value = false
  }
}

// 打开详情对话框
const openDetailDialog = async (row) => {
  try {
    loading.value = true
    const res = await fetchGoodsRemovalById(row.goodsstopmJxsId)
    if (res.success) {
      currentRemoval.value = res.data
      dialogTitle.value = '下架单据详情'
      isDetailMode.value = true
      isReviewMode.value = false
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取下架单据详情失败')
    }
  } catch (error) {
    logger.error('获取下架单据详情失败', error)
    ElMessage.error('获取下架单据详情失败')
  } finally {
    loading.value = false
  }
}

// 提交审核
const handleSubmitToReview = async (row) => {
  try {
    loading.value = true
    const res = await fetchGoodsRemovalById(row.goodsstopmJxsId)
    if (res.success) {
      currentRemoval.value = res.data
      dialogTitle.value = '提交审核'
      isReviewMode.value = true
      isDetailMode.value = false
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取下架单据详情失败')
    }
  } catch (error) {
    logger.error('获取下架单据详情失败', error)
    ElMessage.error('获取下架单据详情失败')
  } finally {
    loading.value = false
  }
}

// 删除下架单据
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除该下架单据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        loading.value = true
        const res = await deleteGoodsRemoval(row.goodsstopmJxsId)
        if (res.success) {
          ElMessage.success('删除成功')
          fetchRemovalData()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        logger.error('删除下架单据失败', error)
        ElMessage.error('删除失败')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {})
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  currentRemoval.value = null
  isReviewMode.value = false
  isDetailMode.value = false
}

onMounted(() => {
  fetchRemovalData()
})
</script>

<template>
  <!-- 商品介绍预览对话框 -->
  <el-dialog
    v-model="previewVisible"
    title="商品介绍预览"
    width="40%"
    align-center
    destroy-on-close
  >
    <ViewHTML :content="previewContent" />
  </el-dialog>

  <!-- 添加/编辑对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsRemoval
      :initial-data="currentRemoval"
      :is-review="isReviewMode"
      :is-detail="isDetailMode"
      @success="fetchRemovalData"
      @close="closeDialog"
    />
  </el-dialog>

  <div class="main-container">
    <!-- 搜索和操作区域 -->
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields">
          <el-form-item label="下架单号">
            <el-input
              v-model="queryFields.goodsstopmJxsId"
              placeholder="请输入下架单号"
              clearable
              style="width: 240px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item style="width: 240px" label="审核状态">
            <el-select v-model="queryFields.billState" placeholder="请选择状态" clearable>
              <el-option label="未提交审核" :value="REQUEST_STATE.DRAFT" />
              <el-option label="正在审核" :value="REQUEST_STATE.REVIEWING" />
              <el-option label="已审核" :value="REQUEST_STATE.APPROVED" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            新增下架单据
          </el-button>
        </el-form-item>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData">
        <el-table-column prop="goodsstopmJxsId" label="下架单号" min-width="180" align="center" />
        <el-table-column prop="operator" label="操作员" min-width="120" align="center" />
        <el-table-column label="操作时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.optTime) }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.billState === 0 ? 'info' : row.billState === 1 ? 'success' : 'warning'"
            >
              {{ row.billState === 0 ? '未审核' : row.billState === 1 ? '审核完成' : '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="openDetailDialog(row)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              详情
            </el-button>
            <el-button
              v-if="row.billState === REQUEST_STATE.DRAFT"
              type="primary"
              size="small"
              @click="openEditDialog(row)"
            >
              <template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑
            </el-button>
            <el-button
              v-if="row.billState === REQUEST_STATE.DRAFT"
              type="success"
              size="small"
              @click="handleSubmitToReview(row)"
            >
              <template #icon>
                <el-icon><LineMdUpload /></el-icon>
              </template>
              提交审核
            </el-button>
            <el-popconfirm
              v-if="row.billState === REQUEST_STATE.DRAFT"
              placement="top-start"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :title="`确定要删除该下架单据吗？`"
              width="250"
              confirm-button-type="danger"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <template #icon>
                    <el-icon><LineMdTrash /></el-icon>
                  </template>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
